/*
 * @lc app=leetcode.cn id=654 lang=typescript
 *
 * [654] 最大二叉树
 */

// @lc code=start
/**
 * Definition for a binary tree node.
 * class TreeNode {
 *     val: number
 *     left: TreeNode | null
 *     right: TreeNode | null
 *     constructor(val?: number, left?: TreeNode | null, right?: TreeNode | null) {
 *         this.val = (val===undefined ? 0 : val)
 *         this.left = (left===undefined ? null : left)
 *         this.right = (right===undefined ? null : right)
 *     }
 * }
 */

function constructMaximumBinaryTree(nums: number[]): TreeNode | null {
  const construct = (nums: number[], start: number, end: number) => {
    if (start > end) return null;
    let maxIndex = start;
    for (let i = start + 1; i <= end; i++) {
      if (nums[i] > nums[maxIndex]) {
        maxIndex = i;
      }
    }
    const node = new TreeNode(nums[maxIndex]);
    node.left = construct(nums, start, maxIndex - 1);
    node.right = construct(nums, maxIndex + 1, end);
    return node;
  };

  return construct(nums, 0, nums.length - 1);
}
// @lc code=end
